import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import { Upload, message } from 'antd';
import { useState } from 'react';
import { getToken, uploadActionUrl } from '../utils/tools';
const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
};
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只能上传jpj/png格式图片!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

const ImageUpLoad = (props) => {
  const [loading, setLoading] = useState(false);
  const {imageUrl,setImageUrl} = props

  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
        //base64格式
    //   getBase64(info.file.originFileObj, (url) => {
    //     setLoading(false);
    //     setImageUrl(url);
    //   });
    // info时上传成功得到的对象
    // 得到图片路径 info.file.response.pathFile    
        // console.log(info);
        // console.log(info.file.response.path);
        setLoading(false);
        setImageUrl(info.file.response.path  );
    }
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        点击上传图片
      </div>
    </div>
  );
  return (
    <>
      <Upload
        //服务器端这个图片的参数名称
        name="pic"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        //上传地址 接口API
        action={uploadActionUrl}
        //不是通过axios发送请求 需要单独设置token
        headers={{
            Authorization:'bearer ' + getToken()
        }}
        beforeUpload={beforeUpload}
        onChange={handleChange}
      >
        {imageUrl ? (
          <img
            src={imageUrl}
            alt="avatar"
            style={{
              width: '100%',
            }}
          />
        ) : (
          uploadButton
        )}
      </Upload>
    </>
  );
};
export default ImageUpLoad;